
/******************************************************************************/
/*!
\file   CVertexBuffer.cpp
\author David Seah Seng Chong
\par    email: sengchong.seah\@digipen.edu
\par    DigiPen login: sengchong.seah
\par    Course: GAM200
\date   03/01/2012
\brief
  Header file
  Graphics Engine

    Copyright (C) 2011 DigiPen Institute of Technology.
    Reproduction or disclosure of this file or its contents without the
    prior written consent of DigiPen Institute of Technology is prohibited.
*/
/******************************************************************************/
#include "PreCompiledHeader.h"
#include "CVertexBuffer.hpp"


CVertexBuffer::CVertexBuffer()
{
	m_pVB = NULL;
	m_numVertices = 0;
	m_FVF = 0;
	m_VertexSize = 0;
}

bool CVertexBuffer::CreateBuffer( LPDIRECT3DDEVICE9 pDevice, UINT numVertices, DWORD FVF, UINT vertexSize, BOOL dynamic )
{
	Release();
	m_numVertices = numVertices;
	m_FVF = FVF;
	m_VertexSize = vertexSize;

	// Dynamic buffers can't be in D3DPOOL_MANAGED
	D3DPOOL pool = dynamic ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED;
	DWORD usage = dynamic ? D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC : D3DUSAGE_WRITEONLY;
	if ( FAILED( pDevice->CreateVertexBuffer(m_numVertices * m_VertexSize , usage, m_FVF, pool, &m_pVB, NULL ) ) )
	{
		return FALSE;
	}
	return true;
}

void CVertexBuffer::Release()
{
    // release resource when done.
    if( m_pVB != NULL)
    {
        m_pVB->Release();
        m_pVB = NULL;
    }
    m_numVertices = 0;
    m_FVF = 0;
    m_VertexSize = 0;
}

bool CVertexBuffer::SetData( UINT numVertices, void *pVertices,  DWORD flags = D3DLOCK_DISCARD)
{
  if ( m_pVB == NULL )
  {
      return FALSE;
  }

  char* pData;
  //Lock the vertex buffer
  if ( FAILED( m_pVB->Lock( 0, numVertices*m_VertexSize, (void**)&pData, flags ) ) )
  {
      return FALSE;
  }

  // Copy vertices to vertex buffer
  memcpy( pData, pVertices, numVertices * m_VertexSize );

  // Unlock vertex buffer
  if ( FAILED( m_pVB->Unlock() ) )
  {
      return FALSE;
  }

  return TRUE;
}

void CVertexBuffer::Render(LPDIRECT3DDEVICE9& pDevice, UINT numPrimitives, D3DPRIMITIVETYPE primitiveType )
{
  if ( pDevice == NULL )
  {
    return;
  }
  
  pDevice->SetStreamSource( 0, m_pVB, 0, m_VertexSize );
  pDevice->SetFVF(m_FVF);
  pDevice->DrawPrimitive( primitiveType, 0, numPrimitives );
}


